package com.fourtwenty.hemptress;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.jibble.pircbot.IrcException;
import org.jibble.pircbot.NickAlreadyInUseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fourtwenty.hemptress.plugin.PluginEvent;
import com.fourtwenty.hemptress.plugin.PluginLoadingException;

public class Hemptress extends PluginEventBot {
	private static final Logger LOG = LoggerFactory.getLogger(Hemptress.class);
	
	private String commandPrefix = "!";
	
	public Hemptress() {
		this.setMessageDelay(50);
		super.init();
	}
	
	public Hemptress(HemptressConfig conf) throws PluginLoadingException {
		this();
		
		this.setName(conf.getName());
		try {
			this.connect(conf.getServer(), conf.getPort());
		} catch (NickAlreadyInUseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IrcException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		this.joinChannel("#hemp-test");
		this.joinChannel("#420");
		this.setVerbose(true);
	}

	public static void main(String[] args) throws Exception {
		Hemptress h = new Hemptress(new HemptressConfig());
	}

	@Override
	protected void onMessage(String channel, String sender, String login,
			String hostname, String message) {
		
		String[] command = parseCommand(message);
		Map<String, String> params = new HashMap<>();
		params.put("channel", channel);
		params.put("sendernick", sender);
		params.put("senderlogin", login);
		params.put("senderhostname", hostname);
		
		if(command != null && command.length > 1) {
			params.put("command", command[0]);
			params.put("params", command[1]);
			triggerEvent(PluginEvent.COMMAND, params);
		} else {
			params.put("message", message);
		}
		
		super.onMessage(channel, sender, login, hostname, message);
	}

	public String[] parseCommand(String message) {
		if(message.startsWith(this.getNick())) {
			//Strip. "Bot, tell" or "Bot tell"
			return parseSub(message.replaceFirst("^" + this.getNick() + "[:,;\\.]? ", ""));
		} else if(message.startsWith(this.commandPrefix)) {
			return parseSub(message);
		}
		
		return null;
	}
	
	//at this point we know it's a command: command args
	public String[] parseSub(String afterPrefixes) {
		if(afterPrefixes.startsWith(this.commandPrefix)) {
			return parseSub(afterPrefixes.substring(1));
		}
		
		String[] results = {"",""};
		String[] split = afterPrefixes.split("\\s");
		
		if(split.length < 1) {
			return null;
		}
		
		results[0] = split[0];
		results[1] = afterPrefixes.substring(split[0].length()).trim();
		
		return results;
	}
}
